using System.IO;
using System.Xml.Serialization;

namespace Krile.Imported.Snippets
{
    static partial class Files
    {
        /// <summary>
        /// Serialize object to XML file.
        /// </summary>
        /// <typeparam name="Type">Serialize type</typeparam>
        /// <param name="fpath">Destination file path</param>
        /// <param name="cfgclass">Serialize instance</param>
        public static void SaveXML<Type>(string fpath, Type cfgclass)
        {
            XmlSerializer xsz = new XmlSerializer(typeof(Type));
            using (FileStream fs = new FileStream(fpath, FileMode.Create, FileAccess.Write))
            {
                xsz.Serialize(fs, cfgclass);
            }
        }

        /// <summary>
        /// Deserialize object from XML file.
        /// </summary>
        /// <typeparam name="Type">Deserialize type</typeparam>
        /// <param name="fpath">Origin file path</param>
        /// <param name="raiseFileNotFoundException">Reise FileNotFoundException If required file isn't exists</param>
        /// <returns>Deserialized object</returns>
        public static Type LoadXML<Type>(string fpath, bool raiseFileNotFoundException)
        {
            if (!System.IO.File.Exists(fpath))
            {
                if (raiseFileNotFoundException)
                    throw new FileNotFoundException(fpath + "is not found.");
                else
                    return default(Type);
            }
            XmlSerializer xsz = new XmlSerializer(typeof(Type));
            using (FileStream fs = new FileStream(fpath, FileMode.Open, FileAccess.Read))
            {
                return (Type)xsz.Deserialize(fs);
            }
        }
    }
}
